package com.android.qjpmc.widget.retrofithelper.interceptor;

import android.os.Build;
import android.text.TextUtils;

import com.android.qjpmc.manager.AccountManager;
import com.orhanobut.logger.Logger;
import com.android.qjpmc.widget.utils.AppUtils;
import com.android.qjpmc.widget.utils.CommonUtils;
import com.android.qjpmc.widget.utils.DisplayUtils;
import com.android.qjpmc.widget.utils.UIUtils;
import com.android.qjpmc.widget.retrofithelper.encrypt.RSAEncryptManager;
import com.android.qjpmc.widget.retrofithelper.utils.NetUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

public class SecurityInterceptor2 implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String sign = "";
        Request.Builder builder = request.newBuilder();
        if (request.method() == "GET") {
            List<String> valueByName = CommonUtils.getValueByName(request.url().toString());
            builder.header("params", valueByName.toString());
        } else if ("POST".equals(request.method()) || "PATCH".equals(request.method())) {
            String url = request.url().toString();
            String encodeURL = "";//URL编码后的请求url
            String encodeSortParams = "";//URL编码后的升序参数体
            HashMap<String, String> paramsMap = new HashMap<>();
            //step1.1  将请求的URI路径进行URL编码
            encodeURL = URLEncoder.encode(url, "utf-8");
            Logger.d("url=" + url);
            Logger.d("encode_url=" + encodeURL);
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                int bodySize = body.size();
                for (int i = 0; i < bodySize; i++) {
                    if (!TextUtils.isEmpty(body.encodedValue(i))) {
                        paramsMap.put(body.name(i), body.value(i));
                        sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                    }
                }

                sb.delete(sb.length() - 1, sb.length());
                Logger.d("║ RequestParams:{" + sb.toString() + "}");
                Collection<String> keyset = paramsMap.keySet();
                List<String> list = new ArrayList<>(keyset);
                //step1.2   对key键值按字典升序排序
                Collections.sort(list);
                StringBuilder sortParams = new StringBuilder();
                int sortParamSize = list.size();
                //step1.3   将第2步中排序后的参数(key=value)用&拼接起来，并进行URL编码。
                for (int i = 0; i < sortParamSize; i++) {
                    String value = paramsMap.get(list.get(i));
                    if (!TextUtils.isEmpty(value)) {
                        // sortParams.append(list.get(i) + "=" + value);
                       /* if (i != sortParamSize - 1) {
                            sortParams.append("&");
                        }*/
                        sortParams.append(value);
                    }
                }
                String paramsString = sortParams.toString();
                Logger.d("数据字典升序后:key键值=" + paramsString);
                encodeSortParams = URLEncoder.encode(paramsString, "utf-8");//进行URL编码的 key键值
                Logger.d("数据字典升序并encode=" + encodeSortParams);
                //step1.4   将HTTP请求方式（GET或者POST）以及第1步和第3步中的字符串用&拼接起来。
                StringBuilder bufferStep1 = new StringBuilder();
              /*  bufferStep1.append(request.method());
                bufferStep1.append("&");
                bufferStep1.append(encodeURL);
                bufferStep1.append("&");*/
                bufferStep1.append(encodeSortParams);
                Logger.d("拼接后的step1=" + bufferStep1.toString());

                try {

                    // 加密
                    sign = RSAEncryptManager.encryptByPrivateString(bufferStep1.toString());


                    String signAli = RSAEncryptManager.getSign(paramsMap, RSAEncryptManager.getPublicKeyFromAssets(), true);
                    // 解密
                    String privateSign = RSAEncryptManager.decryptByPrivateString(signAli);
                    Logger.d("aliSign" + signAli);
                    Logger.d("rsaPublicKey" + sign);
                    Logger.d("rsaPrivateKey" + privateSign);
                    paramsMap.put("sign", sign);
                    injectParamsIntoBody(paramsMap, request, builder);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (AccountManager.getInstance().isLogin())
            builder.addHeader("Pfx-AccessToken", AccountManager.getInstance().getLoginData(null).accessToken);
        builder.addHeader("Pfx-AppVersion", AppUtils.getAppInfo().getVersionCode() + "");
        builder.addHeader("Pfx-APIVersion", AppUtils.getAppInfo().getVersionName());
        builder.addHeader("Pfx-OS", "Android");
        builder.addHeader("Pfx-OS-Version", Build.VERSION.RELEASE);
        builder.addHeader("Pfx-Android-API", Build.VERSION.SDK_INT + "");

        builder.addHeader("Pfx-Device-Name", Build.MODEL);
        builder.addHeader("Pfx-Device-Manufacturer", Build.MANUFACTURER);
        builder.addHeader("Pfx-Network", NetUtils.getNetworkState());
        builder.addHeader("Pfx-Screen-Size", DisplayUtils.getScreenInch() + "");
        builder.addHeader("Pfx-Display-Metrics", DisplayUtils.loggerDisplayMetrics() + "");
        builder.addHeader("Pfx-Resolution", DisplayUtils.getScreenWidth(UIUtils.getContext()) + "*" + DisplayUtils.getScreenHeight(UIUtils.getContext()));
        Request buildRequest = builder.build();
        return chain.proceed(buildRequest);
    }

    private void injectParamsIntoBody(HashMap<String, String> paramsMap, Request request, Request.Builder requestBuilder) {

        if (request.body() instanceof FormBody) {
            FormBody.Builder newFormBodyBuilder = new FormBody.Builder();
            if (paramsMap.size() > 0) {
                for (Object o : paramsMap.entrySet()) {
                    Map.Entry entry = (Map.Entry) o;
                    newFormBodyBuilder.add((String) entry.getKey(), (String) entry.getValue());

                }
            }

            FormBody oldFormBody = (FormBody) request.body();
            int paramSize = oldFormBody.size();
            if (paramSize > 0) {
                for (int i = 0; i < paramSize; i++) {
                    if (!TextUtils.isEmpty(oldFormBody.value(i)))
                        newFormBodyBuilder.add(oldFormBody.name(i), oldFormBody.value(i));
                }
            }

            requestBuilder.post(newFormBodyBuilder.build());

        } else if (request.body() instanceof MultipartBody) {
            MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

            for (Object o : paramsMap.entrySet()) {
                Map.Entry entry = (Map.Entry) o;
                multipartBuilder.addFormDataPart((String) entry.getKey(), (String) entry.getValue());
            }

            List<MultipartBody.Part> oldParts = ((MultipartBody) request.body()).parts();
            if (oldParts != null && oldParts.size() > 0) {
                for (MultipartBody.Part part : oldParts) {
                    multipartBuilder.addPart(part);
                }
            }

            requestBuilder.post(multipartBuilder.build());

        }


    }


}
